const express = require('express');
const Task = require('../model/task');

const todo = express.Router();

todo.get('/task', async(req, res) => {
  let data = await Task.find();
  res.send(data);
})

todo.post('/addTask', async (req, res) => {
  const task = await Task.create({
    title: req.body.title
  });
  res.send(task);
})

todo.get('/deleteTask', async (req, res) => {
  const id = req.query.id;
  await Task.findOneAndDelete({_id: id});
  res.send('ok');
})

todo.get('/clearAll', async (req, res) => {
  // 已完成的全部删除
  await Task.deleteMany({complete: true});
  res.send('ok');
})

todo.post('/updateTask', async (req, res) => {
  const {id, complete} = req.body;
  await Task.updateOne({_id: id}, {complete});
  res.send('ok');
})

todo.post('/modifyTask', async (req, res) => {
  const {id, title} = req.body;
  await Task.updateOne({_id: id}, {title});
  res.send('ok');
})

module.exports = todo;